<template>
  <el-table
    :data="tableDatas.tableData"
    @select-all="selectAll"
    select-on-indeterminate
    @expand-change="handleDetail"
    @selection-change="handleSelectionChange"
    @row-click="rowClickHandle"
    @row-dblclick="detailClick"
    @sort-change="sortChange"
    ref="topictable"
    border
    stripe
    tooltip-effect="light"
    :show-summary="tableDatas.summary"
    :summary-method="getSummaries"
    :span-method="objSpanMethod"
    style="width: 100%"
    max-height="800"
    :row-class-name="tableRowClassName"
    highlight-current-row
    :header-cell-style="{ background: '#DFF1FD', fontWeight: 900 }"
    :tree-props="tableDatas.treeProps"
    row-key="row_key"
    :default-expand-all="tableDatas.defaultExpandAll"
  >
    <!-- <el-table-column type="index" width="50" /> -->

    <el-table-column fixed type="index" align="center">
      <template #header>
        <el-popover ref="appversionId" placement="bottom" :width="260" trigger="click">
          <!-- 配置列面板 -->
          <transition name="fade">
            <div class="content">
              <div>选择要展示的列：</div>
              <!-- <el-checkbox-group v-model="checkedTableColumns"> -->
              <el-checkbox v-for="column in tableDatas.tableHead" v-model="column.show" :key="column.field" :label="column.name" show-overflow-tooltip></el-checkbox>
              <!-- </el-checkbox-group> -->
            </div>
          </transition>
          <template #reference>
            <!-- <i class="el-icon-setting" style="font-size: 22px; cursor: pointer" ></i> -->
            <el-icon @click="visibless = true" class="custom-hover"><Setting /></el-icon>
          </template>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column v-if="tableDatas.selection" type="selection" width="50" />

    <el-table-column
      v-for="(item, index) in tableHeads"
      :key="index"
      :fixed="item.fixed"
      sortable
      min-width="100"
      :align="item.align"
      :label="item.name"
      :prop="item.field"
    >
      <template #default="scope">
        <!-- [name,value] -->
        <span v-if="wmsGlobal.wmsOptions[item.field]" v-html="getValue(item.field, scope.row)"></span>
        <span v-else-if="item.type == 'date'" v-html="fomatDate(scope.row[item.field])"></span>
        <span v-else v-html="scope.row[item.field]"></span>
      </template>
    </el-table-column>

    <el-table-column label="操作" fixed="right" v-if="tableDatas.delete || tableDatas.edit || tableDatas.confirm" min-width="100">
      <template #default="scope">
        <el-button v-if="tableDatas.confirm" type="success" :icon="Check" size="small" circle @click="confirmRow(scope)" />
        <el-button v-if="tableDatas.edit" type="primary" :icon="Edit" size="small" circle @click="editRow(scope)" />
        <el-button v-if="tableDatas.delete" type="danger" :icon="Delete" size="small" circle @click="deleteRow(scope)" />
      </template>
    </el-table-column>
    <!-- <el-table-column  width="60" align="item.align" label="name" ></el-table-column> v-for="(item,index) in tableDatas.tableHead" :key="index"
    <el-table-column  width="60" align="item.align" label="name" ></el-table-column> 
    <el-table-column  width="60" align="item.align" label="name" ></el-table-column>  -->
  </el-table>
  <div class="table-boottom" v-if="!tableDatas.paging">
    <el-pagination
      v-model:current-page="pagination.pageNum"
      v-model:page-size="pagination.maxResult"
      :page-sizes="[15, 50, 100, 200, 500, 1000, 2000, 5000]"
      small="small"
      background="background"
      layout="total, sizes, pager, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleSizeChange"
    />
  </div>
</template>
<script setup name="wmsTable">
import { ref, reactive, computed } from 'vue'
import http from '../utils/http'
import { objAssign, fomatDate, createFromJson, MessageBox } from '@/components/utils/api'
import { Delete, Plus, Edit, Setting,Check } from '@element-plus/icons-vue'
import { useWmsGlobal } from '@/store/wmsGlobal'
const visibless = ref(false)
const topictable = ref()
const wmsGlobal = useWmsGlobal()
const props = defineProps({
  tableDatas: Object
})
const pagination = reactive({
  maxResult: 15,
  pageNum: 1,
  total: 0,
  startPosition: 0
})

const tableDatas = props.tableDatas
const tableHeads = computed(() => {
  if (!tableDatas.tableHead) return []
  return tableDatas.tableHead.filter(item => item.show)
})
const emit = defineEmits(['update:selectDatas', 'editHandle','detailClick'])
const selectAll = () => {}
const handleDetail = () => {}
const handleSelectionChange = data => {
  emit('update:selectDatas', data)
}
const rowClickHandle = () => {}
const detailClick = (row) => {
  emit('detailClick', row)
  if(tableDatas.edit){
    emit('editHandle', {row})
  }
}
const getSummaries = param => {
  const result = []
  param.columns.forEach(item => {
    const sum = tableDatas.sum
    if (sum[item.property]) {
      result.push(sum[item.property])
    } else {
      if (item.no === 0) {
        result.push('')
      } else {
        result.push('')
      }
    }
  })
  // return {serial_number:"编号",menu_level:15}
  return result
}
const objSpanMethod = () => {}
const sortChange = column => {
  if (column.order) {
    tableDatas.body.params.sort = column.prop
    if (column.order === 'ascending') tableDatas.body.params.sortType = 'ASC'
    if (column.order === 'descending') tableDatas.body.params.sortType = 'DESC'
  } else {
    tableDatas.body.params.sort = null
    tableDatas.body.params.sortType = null
  }

  getData()
}
const addSelectDatas = rows => {
  rows.forEach(row => {
    topictable.value.toggleRowSelection(row, undefined)
  })
}
let tableRowClassName = ({ row, rowIndex }) => {
  // 把每一行的索引放进row
  // row.index = rowIndex
  // let index = rowIndex + 1
  if (rowIndex % 2 == 0) {
    return 'warning-row'
  } else {
    return 'warning-rows'
  }
}
let initHead = head => {
  head.forEach(item => {
    ;(item.field = item.tvalue), (item.name = item.tname), (item.show = item.tshow == 0 ? true : false), (item.type = item.ttype)
  })
}
const getHead = () => {
  http
    .POST('/Menu/getTableHead', {
      tableKey: tableDatas.body.head
    })
    .then(data => {
      initHead(data.data)
      tableDatas.tableHead = data.data
      // createFromJson(tableDatas.tableHead)
    })
}
const getData = () => {
  return new Promise((resolve, inj) => {
    objAssign(tableDatas.body.params, pagination)
    http[tableDatas.body.type ? tableDatas.body.type : 'POSTJSON'](tableDatas.body.url, tableDatas.body.params).then(data => {
      tableDatas.tableData = data.data
      if (data.sum && data.sum != null) {
        tableDatas.summary = true
        tableDatas.sum = data.sum
      }
      if (data.total) {
        pagination.total = data.total
      }
      resolve(tableDatas.tableData)
    })
  })
}
getHead()
// getData()
const getName = (scope)=>{
  let msg = ''
  if (scope.row.name) {
   msg = '确定删除 '+scope.row.name +' 吗'
  }else{
    msg = '确定删除第 '+(scope.$index +1) + ' 行数据吗'
  }
  return msg;
}
const deleteRow = (scope) => {
  const msg = getName(scope);
  MessageBox(msg, () => {
    const params = {}
    for (const key in tableDatas.delete.params) {
      params[key] = row[key]
    }
    http.POST(tableDatas.delete.url, params).then(data => {
      if (data.code === 200) {
        getData()
      }
    })
  })
}
const editRow = row => {
  emit('editHandle', row)
}

const confirmRow = scope => {
  emit('confirmHandle', scope)
  // let msg;
  // if (scope.row.name) {
  //  msg = '确认 '+scope.row.name +' 吗'
  // }else{
  //   msg = '确认第 '+(scope.$index +1) + ' 行数据吗'
  // }
  // MessageBox(msg,()=>{
  //   emit('confirmHandle', scope)
  // })
  
}

const getValue = (field, row) => {
  const arr = wmsGlobal.wmsOptions[field]
  for (let index = 0; index < arr.length; index++) {
    if (row[field] == arr[index].value) {
      return arr[index].name
    }
  }
  return row[field]
}
const handleSizeChange = value => {
  pagination.startPosition = (pagination.pageNum - 1) * pagination.maxResult
  getData()
}
defineExpose({ getData, getHead, addSelectDatas })
</script>


<style lang="scss">
.el-table .warning-row td {
  background: #f5ffff;
}

.el-table .warning-rows td {
  background: #f5f5f5;
}
.table-boottom {
  display: flex;
  flex-direction: row-reverse;
  align-items: center;
  margin-top: 20px;
}
.content {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
</style>